package com.deco.back.bf.common;

import com.deco.back.properties.ConstantsProperties;
import com.deco.back.utils.CommonUtil;
import com.deco.back.utils.NameMaker;
import com.deco.domain.vo.common.FileUploadInfoVo;
import com.deco.domain.vo.sys.CmsMediaVo;
import com.deco.domain.vo.sys.CmsMenuVo;
import com.deco.service.sys.CmsMediaService;
import com.free.common.vo.ResultModel;
import com.free.exception.SystemException;
import com.free.ext.logger.FreeLogger;
import com.free.ext.logger.FreeLoggerFactory;
import com.free.files.FileManagers;
import com.free.utils.DateUtils;
import com.free.utils.crypt.MD5Crypt;
import com.sun.media.jfxmediaimpl.MediaUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.beans.MethodDescriptor;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 功能概述:
 * </p>
 * <p>
 * 功能详述:
 * </p>
 */
@Component
public class FileUploadBf {
    /*========================================================================*
     *                         Public Fields (公共属性)
     *========================================================================*/

    private static final FreeLogger LOG = FreeLoggerFactory.getLogger(FileUploadBf.class);

    /*========================================================================*
     *                         Private Fields (私有属性)
     *========================================================================*/

    @Value(value = "${sys.img.root}")
    private String fileRoot;

    @Value(value = "${sys.img.directory}")
    private String fileDirectory;

    @Value(value = "${sys.img.domain}")
    private String hostDomain;

    @Autowired
    CmsMediaService cmsMediaService;

    /*========================================================================*
     *                         Construct Methods (构造方法)
     *========================================================================*/

    /*========================================================================*
     *                         Public Methods (公有方法)
     *========================================================================*/

    public ResultModel upload(MultipartFile file, FileUploadInfoVo uploadInfoVo) throws IOException, SystemException {
        if(file.isEmpty()){
            return ResultModel.success();
        }
        String path = fileName(file, uploadInfoVo);
        LOG.info("最终文件目录{}",path);
        ResultModel res = FileManagers.getFiler().upload(file.getBytes(),path);
        if(res.isSuccess()){
            res = save(uploadInfoVo);
            if(res.isSuccess()){
                res.setData(uploadInfoVo.getRelativePath());
            }
        }
        return res;
    }

    /*========================================================================*
     *                         Private Methods (私有方法)
     *========================================================================*/

    private ResultModel save(FileUploadInfoVo uploadInfoVo){
        CmsMediaVo mediaVo = new CmsMediaVo();
        if(uploadInfoVo.getSaveDB()){
            Timestamp createTime = new Timestamp(System.currentTimeMillis());
            mediaVo.setCreateTime(createTime);
            mediaVo.setName(uploadInfoVo.getName());
            mediaVo.setRelativePath(uploadInfoVo.getRelativePath());
            mediaVo.setRootPath(uploadInfoVo.getRootPath());
            mediaVo.setSize(uploadInfoVo.getSize());
            mediaVo.setImgWidth(uploadInfoVo.getWidth());
            mediaVo.setExtension(uploadInfoVo.getExtension());
            mediaVo.setTypeId(uploadInfoVo.getTypeId());
            return cmsMediaService.save(mediaVo);
        }
        return ResultModel.success();
    }

    private String fileName(MultipartFile file,FileUploadInfoVo uploadInfoVo) throws IOException {
        String imgParam = "";
        BufferedImage img = ImageIO.read(file.getInputStream());
        if(img != null){
            imgParam = "_" + img.getWidth() + "x" + img.getHeight();
            uploadInfoVo.setWidth(img.getWidth());
            uploadInfoVo.setHeight(img.getHeight());
        }
        String[] fileNmArr = getOrgFileNameArr(file.getOriginalFilename());
        StringBuffer fileNm = new StringBuffer();
        fileNm.append(filePath(uploadInfoVo))
                .append(File.separator)
                .append(NameMaker.getInstance().getStr32() + imgParam)
                .append(".")
                .append(fileNmArr[1]);

        uploadInfoVo.setName(file.getName());
        uploadInfoVo.setRootPath(fileRoot);
        uploadInfoVo.setRelativePath(fileNm.substring(fileRoot.length()).replaceAll("\\\\", "/"));
        uploadInfoVo.setSize(CommonUtil.fmtSize(file.getSize()));
        uploadInfoVo.setName(file.getOriginalFilename());
        uploadInfoVo.setExtension(fileNmArr[1]);
        return fileNm.toString();
    }

    private String filePath(FileUploadInfoVo uploadInfoVo){
        String type = "sys";
        if(!uploadInfoVo.getSaveDB()){
            type = "tmp";
        }
        StringBuffer strBuf = new StringBuffer();
        LOG.info("系统文件家目录:{},文件目录{}",fileRoot,fileDirectory);
        return strBuf.append(fileRoot)
                .append(fileDirectory)
                .append(File.separator)
                .append(DateUtils.now(DateUtils.FormatEnum.yyyyMM))
                .append(File.separator)
                .append("m" + type).toString();
    }

    private String[] getOrgFileNameArr(String fileName){
        int n = fileName.lastIndexOf(".");
        return new String[] { fileName.substring(0, n), fileName.substring(n + 1) };
    }
}
